package com.huashizhaoxi.lionapp.controller;

import com.huashizhaoxi.lionapp.entity.Banner;
import com.huashizhaoxi.lionapp.entity.Result;
import com.huashizhaoxi.lionapp.entity.User;
import com.huashizhaoxi.lionapp.service.BannerService;
import com.huashizhaoxi.lionapp.service.UserService;
import com.huashizhaoxi.lionapp.utils.FileUtils;
import com.huashizhaoxi.lionapp.utils.JwtUtils;
import org.apache.ibatis.mapping.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;

    @Autowired
    private UserService userService;

    private FileUtils fileUtils;
    private JwtUtils jwtUtils;

    @GetMapping("/catch/all")
    public Result getAllBanner() {
        List<Banner> bannerList = bannerService.getAllBanner();
        if(bannerList != null) {
            return Result.success("获取轮播图列表成功", bannerList);
        } else {
            return Result.error("获取轮播图列表失败");
        }
    }

    // 上传轮播图片到本地，返回url
    @PostMapping("/upload")
    @ResponseBody
    public Result uploadBanner(@RequestParam("file") MultipartFile file) {
        if (Objects.isNull(file) || file.isEmpty()) {
            //判断非空
            return Result.error("文件为空");
        }
        try{
            String localPath="C:/Users/Administrator/images/";
            String upPath = "https://www.huashizhaoxi.icu:81/images/";
            String fileName = file.getOriginalFilename();
            fileName = FileUtils.getFileName(fileName);
            File dest = new File(localPath + fileName);
            String url = upPath+fileUtils.upload(file,localPath,fileName);
            return Result.success("上传成功", url);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }


    // 向数据库中插入轮播图信息，接收List<Banner>，先清空表再插入
    @PostMapping("/insert")
    @ResponseBody
    public Result insertBanner(@RequestBody List<Banner> bannerList,@RequestHeader("mytoken") String token) {
        Map<String,Object> map = jwtUtils.parseJwt(token);
        if(map == null) {
            return Result.error("token无效");
        }
        User user = userService.getUserByOpenId((String) map.get("open_id"));
        if(user.getRole()==0){
            return Result.error("权限不足");
        }
        if(bannerList != null) {
            bannerService.deleteAllBanner();
            bannerService.insertBanner(bannerList);
            return Result.success("插入轮播图信息成功",null);
        } else {
            return Result.error("插入轮播图信息失败");
        }
    }
}
